/*

Exemplo de utilizacao:

<script src='/js/ajax_globals.js'></script>
<script language='javascript'>
	var global_functions = new Global_Functions();
	
	var xmlhttp = global_functions.ajax();
</script>


PARA CRIAR UMA NOVA FUNÇÃO COM ACESSO EXERNO É NECESSARIO DECLARA-LA

*/

function Global_Functions(){
	
	this.setLocaleNull = setLocaleNull;
	this.is_array      = is_array;
	this.url_decode    = url_decode;
	this.url_encode    = url_encode;
	this.ajax          = ajax;
	this.rTrim         = rTrim;
	this.lTrim         = lTrim;
	this.trim          = trim;
	this.checkAll      = checkAll;
	this.setObjClass   = setObjClass;
	this.validaEmail   = validaEmail;
	this.MM_showHideLayers = MM_showHideLayers;
	this.alterForm     = alterForm;

	//Apaga todos os elementos de um select
	function setLocaleNull(selectForm)
	{
		var qtdeformLocale = selectForm.length;
		if( qtdeformLocale > 0 )
		{
			while (qtdeformLocale != 0)
			{//exclui elementos antigos
				selectForm.options[0] = null;
				qtdeformLocale = selectForm.length;
			}
		}
	}

	//Verifica se é array
	function is_array(obj) {
		return (obj.constructor.toString().indexOf("Array") == -1)
	}

	function url_decode(str) {
		 var n, strCode, strDecode = "";

		 for (n = 0; n < str.length; n++) {
			  if (str.charAt(n) == "%") {
				   strCode = str.charAt(n + 1) + str.charAt(n + 2);
				   strDecode += String.fromCharCode(parseInt(strCode, 16));
				   n += 2;
			  } else if (str.charAt(n) == "+") {
				   strCode = str.charAt(n);
				   strDecode += " ";
			  } else {
				   strDecode += str.charAt(n);
			  }
		 }
		 return strDecode;
	}

	function url_encode(str) {
		 var hex_chars = "0123456789ABCDEF";
		 var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
		 var n, strCode, hex1, hex2, strEncode = "";

		 for(n = 0; n < str.length; n++){
			  if (noEncode.test(str.charAt(n))){
				   strEncode += str.charAt(n);
			  }
			  else{
				   strCode = str.charCodeAt(n);
				   hex1 = hex_chars.charAt(Math.floor(strCode / 16));
				   hex2 = hex_chars.charAt(strCode % 16);
				   strEncode += "%" + (hex1 + hex2);
			  }
		 }
		 return strEncode;
	}


	//funcao de requisicao ajax abaixo alguns exemplos de utilizacao
	/*
	exemplo 1: ( assincrono )
		var xmlhttp = ajax();
		xmlhttp.open("GET","grava_pesq.php?satisfaction="+satisfaction+"&busca="+formType+"&queryId="+queryId);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) {
				var conteudo = url_decode(xmlhttp.responseText);
			}
		}
		xmlhttp.send(null);


	exemplo 2:  ( sincrono )
		var xmlhttp = ajax();
		xmlhttp.open("GET","grava_pesq.php?satisfaction="+satisfaction+"&busca="+formType+"&queryId="+queryId,false);
		xmlhttp.send(null);
		var conteudo = url_decode(xmlhttp.responseText);

	exemplo 3: ( POST assincrono )
		var xmlhttp = ajax();
		xmlhttp.open("POST", "/gen/funcoesTop.php");
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=ISO-8859-1");
		xmlhttp.onreadystatechange=function(){
			if (xmlhttp.readyState==4){
				var rightDomain = url_decode(xmlhttp.responseText);
			}
		}
		xmlhttp.send('vars=bla&vars2=bla2');
	*/


	function ajax(){
		 try{
			  xmlhttp = new XMLHttpRequest();
		 }
		 catch(ee){
			  try{
				   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			  }
			  catch(e){
				   try{
					    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				   }
				   catch(E){
					    xmlhttp = false;
				   }
			  }
		 }
		 return xmlhttp;
	}

	function rTrim(str){
		var espaco = String.fromCharCode(32);
		var tamanho = str.length;
		var temp = "";
		if(tamanho < 0) {
			return "";
		}

		var temp2 = tamanho - 1;
		while(temp2 > -1){
			if(str.charAt(temp2) == espaco){
				// não faz nada
			}else{
				temp = str.substring(0, temp2 + 1);
				break;
			}
			temp2--;
		}
		return temp;
	}

	function lTrim(str){
		var espaco = String.fromCharCode(32);
		var tamanho = str.length;
		var temp = "";
		if(tamanho < 0) {
			return "";
		}

		var temp2 = 0;

		while(temp2 < tamanho){
			if(str.charAt(temp2) == espaco){
				// não faz nada
			}else{
				temp = str.substring(temp2, tamanho);
				break;
			}
			temp2++;
		}
		return temp;
	}

	function trim(str) {
		if(str.length < 1) {
			return "";
		}
		str = rTrim(str);
		str = lTrim(str);    

		if(str == "") {
			return "";
		} else {
			return str;
		}
	}

	//seta os checkbox como selecionados ou não. Passar o id dos checkbox e o status (true ou false)
	function checkAll(filter,stat){
		var arrayFields = document.getElementsByTagName('input');
		for( var i=0; i<arrayFields.length; i++ ){
			if( arrayFields[i].type == 'checkbox' && arrayFields[i].id == filter ){
				arrayFields[i].checked = stat;
			}
		}
	}

	//muda classes primeiro parametro é o id do objeto, o segundo é a classes (estilo css) a ser aplicado
	function setObjClass(obj,classe)
	{
		var objeto = document.getElementById(obj);
		var classeAtual = objeto.getAttribute('class');
		if(!classeAtual == "")
		{
			objeto.removeAttribute('class');
		}
		objeto.setAttribute('class',classe);
		objeto.className = classe;
	}

	//valida email (passar o email)
	function validaEmail(strmail){
		var strmail = document.getElementById('campoEmail').value;
		var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
		if (!strmail.match(re)) {
			return false;
		}
	}
	
	function inArray( arraySearch, stringSearch ){
		flagReturn = 0;
		var i = arraySearch.length - 1;
		if (i >= 0) {
			do {
				if (arraySearch[i] == stringSearch) {
					flagReturn=1;
				}
			} while (i--);
		}
		return flagReturn;
	}

	function utf8_decode ( str_data ) {
		var tmp_arr = [], i = ac = c = c1 = c2 = 0;

		while ( i < str_data.length ) {
			c = str_data.charCodeAt(i);
			if (c < 128) {
				tmp_arr[ac++] = String.fromCharCode(c);
				i++;
			}
			else if ((c > 191) && (c < 224)){
				c2 = str_data.charCodeAt(i+1);
				tmp_arr[ac++] = String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = str_data.charCodeAt(i+1);
				c3 = str_data.charCodeAt(i+2);
				tmp_arr[ac++] = String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return tmp_arr.join('');
	}

	function utf8_encode ( str_data ) {
		str_data = str_data.replace(/\r\n/g,"\n");
		var tmp_arr = [], ac = 0;

		for (var n = 0; n < str_data.length; n++) {
			var c = str_data.charCodeAt(n);
			if (c < 128) {
				tmp_arr[ac++] = String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)){
				tmp_arr[ac++] = String.fromCharCode((c >> 6) | 192);
				tmp_arr[ac++] = String.fromCharCode((c & 63) | 128);
			}
			else {
				tmp_arr[ac++] = String.fromCharCode((c >> 12) | 224);
				tmp_arr[ac++] = String.fromCharCode(((c >> 6) & 63) | 128);
				tmp_arr[ac++] = String.fromCharCode((c & 63) | 128);
			}
		}
		return tmp_arr.join('');
	}

	function MM_showHideLayers(){
		var i,p,v,obj,args=MM_showHideLayers.arguments;
		for (i=0; i<(args.length-2); i+=3)
		with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { 
			v=args[i+2];
			if (obj.style) { 
				obj=obj.style; 
				if( v=='show' && obj.display == 'none' ){
					v='block';
				}
				else if( v=='show' && (obj.display == 'block' ) ){
					v='none';
				}
				else{
					v=(v=='show')?'block':(v=='hide')?'none':v; 
				}
			}
			obj.display=v; 
		}
		var ImgSel = eval("document.getElementById('"+args[0]+"Seta')");
		if( ImgSel ){
			if( v=='none' ){
				ImgSel.src = "/buscar/img/SetaDescer.gif";
			}
			else{
				ImgSel.src = "/buscar/img/SetaSubir.gif";
			}
		}
	}
	
	function alterForm(value, campoId, action){
		if( value > 0 ){
			var field = document.getElementById(campoId);
			setLocaleNull(field);

			var xmlhttp = ajax();

			xmlhttp.open("GET", "funcoesLocalidade.php?id="+value+"&action="+action);

			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState == 4) {
					var conteudo = url_decode(xmlhttp.responseText);
					var conteudoArray = conteudo.split(";");
					if (conteudoArray.length > 1) {
						for(i = 0; i < conteudoArray.length - 1; i++) {
							var conteudoArrayTemp = conteudoArray[i].split("|");
							field.options[i] = new Option(conteudoArrayTemp[1], conteudoArrayTemp[0], false, false);
						}
						document.getElementById(campoId).disabled = false;
					}
					else{
						document.getElementById(campoId).disabled = true;
					}
				}
			}
			xmlhttp.send(null)
		}
		else{
			var field = document.getElementById(campoId);
			setLocaleNull(field);
		}
	}
}
var ajaxGlobals = new Global_Functions();
